package com.dxy.dxyuser.controller;


import com.dxy.dxycommon.VO.ResultVO;
import com.dxy.dxycommon.VO.UserInfoVO;
import com.dxy.dxycommon.utils.CookieUtil;
import com.dxy.dxycommon.utils.ResultVOUtil;
import com.dxy.dxyuser.DO.UserInfo;
import com.dxy.dxyuser.constant.CookieConstant;
import com.dxy.dxyuser.enums.ResultEnum;
import com.dxy.dxyuser.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 单点登录
     *
     * @param userInfoVO
     * @param response
     * @return
     */
    @RequestMapping(value = "/login", consumes = "application/json")
    public ResultVO login(@RequestBody UserInfoVO userInfoVO, HttpServletResponse response) {
        //1. 数据库里的数据是否匹配
        UserInfo user = userInfoService.checkUser(userInfoVO);
        if (user == null) {
            return ResultVOUtil.error(ResultEnum.LOGIN_PASSWORD_NOT_RIGHT);
        }
        //2. 判断redis里面是否有登录信息，有销毁之前，起到单点登录的作用
        String userId = user.getId();
        if (stringRedisTemplate.hasKey(userId)) {
            String key = stringRedisTemplate.opsForValue().get(userId);
            stringRedisTemplate.delete(key);
        }
        //3. redis设置key=token, value=userInfo; key=id,value=token
        String token = UUID.randomUUID().toString();
        Integer expire = CookieConstant.expire;
        stringRedisTemplate.opsForValue().set(token, user.toString(), expire, TimeUnit.SECONDS);
        stringRedisTemplate.opsForValue().set(user.getId(), token, expire, TimeUnit.SECONDS);
        //4. 存cookie
        CookieUtil.set(response, CookieConstant.USERID, user.getId(), CookieConstant.expire);
        Map map = new HashMap();
        map.put("token", token);
        map.put("userId", user.getId());
        return ResultVOUtil.success(map);
    }

    //todo 1.微信自动登录  2.H5登录  3.注册


}
